#include "ScreenshotWidget.h"
#include "ScreenshotService.h"
#include "log.h"
#include <QTimer>
#include <QPainter>
#include <QFontMetrics>
#include <QMessageBox>
#include <QFileDialog>
#include <QDateTime>
#include <QDir>
#include <QClipboard>
#include <QApplication>
#include <QScreen>
#include <QTextEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStack>
#include <QList>
#include <QFont>
#include <QColorDialog>
#include <QPolygonF>
#include <QPointF>
#include <cmath>

ScreenshotWidget::ScreenshotWidget(QWidget *parent)
    : QWidget(parent)
    , m_isSelecting(false)
    , m_isFinished(false)
    , m_currentTool(DrawTool::None)
    , m_currentColor(Qt::red)
    , m_penWidth(3)
    , m_currentElement(nullptr)
    , m_textEdit(nullptr)
    , m_toolbar(nullptr)
    , m_isPinned(false)
    , m_isDestroying(false)
{
    // 设置窗口属性
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    setCursor(Qt::CrossCursor);
    
    // 设置全屏
    setWindowState(Qt::WindowFullScreen);
    
    // 初始化工具栏
    initToolbar();
    
    // 初始化文字输入框（隐藏）
    m_textEdit = new QTextEdit(this);
    m_textEdit->setVisible(false);
    m_textEdit->setStyleSheet("background-color: rgba(255, 255, 255, 200); border: 2px solid #0078d4;");
    m_textEdit->setFont(QFont("Arial", 12));
    m_textEdit->setAttribute(Qt::WA_TransparentForMouseEvents, false);  // 确保可以接收鼠标事件
    m_textEdit->raise();  // 确保在最上层
    connect(m_textEdit, &QTextEdit::textChanged, this, [this]() {
        update();
    });
}

ScreenshotWidget::~ScreenshotWidget()
{
    logInfo("========== ~ScreenshotWidget 开始析构 ==========");
    
    // 设置析构标志，防止在析构过程中调用虚函数
    // 必须在任何可能触发 paintEvent 的操作之前设置
    logInfo("析构步骤1: 设置 m_isDestroying = true");
    m_isDestroying = true;
    
    // 完全禁用重绘，防止在析构过程中触发 paintEvent
    logInfo("析构步骤2: 设置 WA_DontShowOnScreen 并隐藏窗口");
    setAttribute(Qt::WA_DontShowOnScreen, true);
    hide();
    
    // 处理所有待处理的事件，确保 paintEvent 不会被延迟调用
    logInfo("析构步骤3: 处理待处理事件");
    QApplication::processEvents();
    logInfo("析构步骤3完成: 待处理事件已处理");
    
    // 清理当前绘图元素（必须在最前面）
    logInfo("析构步骤4: 清理当前绘图元素 - m_currentElement: " << (void*)m_currentElement);
    if (m_currentElement) {
        delete m_currentElement;
        m_currentElement = nullptr;
        logInfo("析构步骤4完成: 当前绘图元素已删除");
    }
    
    // 清理绘图元素
    logInfo("析构步骤5: 清理绘图元素列表 - 元素数量: " << m_drawElements.size());
    for (DrawElement* element : m_drawElements) {
        delete element;
    }
    m_drawElements.clear();
    logInfo("析构步骤5完成: 绘图元素列表已清空");
    
    // 清理历史记录
    logInfo("析构步骤6: 清理历史记录 - 历史记录数量: " << m_historyStack.size());
    while (!m_historyStack.isEmpty()) {
        QList<DrawElement*> history = m_historyStack.pop();
        for (DrawElement* element : history) {
            delete element;
        }
    }
    logInfo("析构步骤6完成: 历史记录已清空");
    
    logInfo("========== ~ScreenshotWidget 析构完成 ==========");
}

/**
 * @brief [FDD-2025-03-021][API-005] 设置历史栈上限
 * @param cap 最大快照数（最小5，默认20）
 * @return 实际生效值
 */
int ScreenshotWidget::setHistoryCap(int cap)
{
    // 限制范围：最小5，最大100
    const int MIN_CAP = 5;
    const int MAX_CAP = 100;

    int newCap = qBound(MIN_CAP, cap, MAX_CAP);

    if (newCap != cap) {
        qWarning() << "[E030_INVALID_CAP] Requested cap" << cap
                   << "out of range, adjusted to" << newCap;
    }

    m_historyBudget.cap = newCap;

    // 如果当前栈深度超过新上限，裁剪多余的快照
    while (m_historyStack.size() > m_historyBudget.cap) {
        // Qt 的 QStack 没有直接访问栈底的方法，需要转换为 QList
        QList<QList<DrawElement*>> tempList;
        while (!m_historyStack.isEmpty()) {
            tempList.prepend(m_historyStack.pop());
        }

        // 释放最旧的快照
        if (!tempList.isEmpty()) {
            QList<DrawElement*> oldest = tempList.takeFirst();
            for (DrawElement* elem : oldest) {
                delete elem;
            }
            m_historyBudget.dropped++;
        }

        // 恢复栈
        for (const auto& state : tempList) {
            m_historyStack.push(state);
        }
    }

    m_historyBudget.current = m_historyStack.size();

    qDebug() << "[HistoryBudget] Cap set to" << m_historyBudget.cap
             << "current:" << m_historyBudget.current
             << "dropped:" << m_historyBudget.dropped;

    return m_historyBudget.cap;
}

void ScreenshotWidget::initToolbar()
{
    // 创建工具栏
    m_toolbar = new QWidget(this);
    m_toolbar->setStyleSheet(
        "QWidget { background-color: rgba(0, 0, 0, 180); border-radius: 5px; }"
        "QPushButton { background-color: rgba(255, 255, 255, 100); border: 1px solid rgba(255, 255, 255, 150); "
        "border-radius: 3px; padding: 5px 10px; color: white; min-width: 40px; }"
        "QPushButton:hover { background-color: rgba(255, 255, 255, 150); }"
        "QPushButton:pressed { background-color: rgba(255, 255, 255, 200); }"
        "QPushButton:checked { background-color: rgba(0, 120, 215, 200); }"
    );
    
    QHBoxLayout* toolbarLayout = new QHBoxLayout(m_toolbar);
    toolbarLayout->setSpacing(5);
    toolbarLayout->setContentsMargins(10, 5, 10, 5);
    
    // 创建工具按钮（使用图标）
    m_rectButton = createToolButton("", "矩形工具");
    m_rectButton->setIcon(QIcon(":/resource/svg/rectangle.svg"));
    m_rectButton->setCheckable(true);
    connect(m_rectButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_rectButton);
    
    m_circleButton = createToolButton("", "圆形工具");
    m_circleButton->setIcon(QIcon(":/resource/svg/circle.svg"));
    m_circleButton->setCheckable(true);
    connect(m_circleButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_circleButton);
    
    m_arrowButton = createToolButton("", "箭头工具");
    m_arrowButton->setIcon(QIcon(":/resource/svg/arrow.svg"));
    m_arrowButton->setCheckable(true);
    connect(m_arrowButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_arrowButton);
    
    m_penButton = createToolButton("", "画笔工具");
    m_penButton->setIcon(QIcon(":/resource/svg/pen.svg"));
    m_penButton->setCheckable(true);
    connect(m_penButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_penButton);
    
    m_mosaicButton = createToolButton("", "马赛克工具");
    m_mosaicButton->setIcon(QIcon(":/resource/svg/mosaic.svg"));
    m_mosaicButton->setCheckable(true);
    connect(m_mosaicButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_mosaicButton);
    
    m_textButton = createToolButton("", "文字工具");
    m_textButton->setIcon(QIcon(":/resource/svg/text.svg"));
    m_textButton->setCheckable(true);
    connect(m_textButton, &QPushButton::clicked, this, &ScreenshotWidget::onToolButtonClicked);
    toolbarLayout->addWidget(m_textButton);
    
    toolbarLayout->addSpacing(10);
    
    m_undoButton = createToolButton("", "撤销上一步");
    m_undoButton->setIcon(QIcon(":/resource/svg/undo.svg"));
    connect(m_undoButton, &QPushButton::clicked, this, &ScreenshotWidget::onUndoButtonClicked);
    toolbarLayout->addWidget(m_undoButton);
    
    toolbarLayout->addSpacing(10);
    
    m_saveButton = createToolButton("", "保存截图");
    m_saveButton->setIcon(QIcon(":/resource/svg/setting.svg"));  // 暂时使用设置图标，可以后续替换
    connect(m_saveButton, &QPushButton::clicked, this, &ScreenshotWidget::onSaveButtonClicked);
    toolbarLayout->addWidget(m_saveButton);
    
    m_pinButton = createToolButton("", "置顶在桌面");
    m_pinButton->setIcon(QIcon(":/resource/svg/pin.svg"));
    m_pinButton->setCheckable(true);
    connect(m_pinButton, &QPushButton::clicked, this, &ScreenshotWidget::onPinButtonClicked);
    toolbarLayout->addWidget(m_pinButton);
    
    m_exitButton = createToolButton("", "退出截图");
    m_exitButton->setIcon(QIcon(":/resource/svg/cancel.svg"));
    connect(m_exitButton, &QPushButton::clicked, this, &ScreenshotWidget::onExitButtonClicked);
    toolbarLayout->addWidget(m_exitButton);
    
    m_completeButton = createToolButton("", "完成截图");
    m_completeButton->setIcon(QIcon(":/resource/svg/complete.svg"));
    m_completeButton->setStyleSheet(
        "QPushButton { background-color: rgba(0, 120, 215, 200); border: 1px solid rgba(255, 255, 255, 150); "
        "border-radius: 3px; padding: 5px 10px; color: white; min-width: 40px; font-weight: bold; }"
        "QPushButton:hover { background-color: rgba(0, 120, 215, 255); }"
    );
    connect(m_completeButton, &QPushButton::clicked, this, &ScreenshotWidget::onCompleteButtonClicked);
    toolbarLayout->addWidget(m_completeButton);
    
    m_toolbar->setLayout(toolbarLayout);
    m_toolbar->setVisible(false);
}

QPushButton* ScreenshotWidget::createToolButton(const QString& text, const QString& tooltip)
{
    QPushButton* button = new QPushButton(m_toolbar);
    button->setText(text);
    button->setToolTip(tooltip);
    button->setIconSize(QSize(20, 20));
    return button;
}

void ScreenshotWidget::startScreenshot()
{
    logInfo("========== startScreenshot 开始 ==========");
    
    // 临时设置标志，防止在清理过程中触发 paintEvent
    logInfo("步骤1: 设置 m_isDestroying = true");
    m_isDestroying = true;
    
    // 清理当前绘图元素（必须在清理其他元素之前）
    logInfo("步骤2: 清理当前绘图元素 - m_currentElement: " << (void*)m_currentElement);
    if (m_currentElement) {
        delete m_currentElement;
        m_currentElement = nullptr;
        logInfo("步骤2完成: 当前绘图元素已删除");
    }
    
    // 清理绘图元素
    logInfo("步骤3: 清理绘图元素列表 - 元素数量: " << m_drawElements.size());
    for (DrawElement* element : m_drawElements) {
        delete element;
    }
    m_drawElements.clear();
    logInfo("步骤3完成: 绘图元素列表已清空");
    
    // 清理历史记录
    logInfo("步骤4: 清理历史记录 - 历史记录数量: " << m_historyStack.size());
    while (!m_historyStack.isEmpty()) {
        QList<DrawElement*> history = m_historyStack.pop();
        for (DrawElement* element : history) {
            delete element;
        }
    }
    logInfo("步骤4完成: 历史记录已清空");
    
    // 重置状态（保持 m_isDestroying = true，防止触发 paintEvent）
    logInfo("步骤5: 重置状态");
    m_isSelecting = false;
    m_isFinished = false;
    m_selectionRect = QRect();
    m_startPoint = QPoint();
    m_endPoint = QPoint();
    m_currentTool = DrawTool::None;
    
    // 先截取主屏幕，用于显示（选中区域正常，未选中区域变暗）
    logInfo("步骤6: 捕获主屏幕截图（用于显示）");
    QScreen* primaryScreen = QApplication::primaryScreen();
    if (primaryScreen) {
        m_fullScreenPixmap = ScreenshotService::instance().captureAllScreens();
        logInfo("步骤6完成: 主屏幕截图已捕获 - 尺寸: " << m_fullScreenPixmap.size() 
                << " 屏幕名称: " << primaryScreen->name());
    } else {
        logError("步骤6失败: 无法获取主屏幕");
        m_fullScreenPixmap = QPixmap();
    }
    m_currentPixmap = m_fullScreenPixmap;
    
    // 确保窗口在设置几何之前是隐藏的，防止触发 paintEvent
    logInfo("步骤7: 检查窗口可见性 - isVisible: " << isVisible());
    if (isVisible()) {
        hide();
        logInfo("步骤7: 窗口已隐藏");
    }
    
    // 更新窗口大小和位置（保持 m_isDestroying = true，防止触发 paintEvent）
    logInfo("步骤8: 更新窗口几何");
    QRect totalRect;
    QList<QScreen*> screens = QApplication::screens();
    for (QScreen* screen : screens) {
        totalRect = totalRect.united(screen->geometry());
    }
    logInfo("步骤8: 设置窗口几何 - " << totalRect);
    setGeometry(totalRect);
    logInfo("步骤8完成: 窗口几何已设置");
    
    // 显示工具栏（保持 m_isDestroying = true）
    logInfo("步骤9: 显示工具栏");
    m_toolbar->setVisible(true);
    updateToolbarPosition();
    logInfo("步骤9完成: 工具栏已显示");
    
    // 确保窗口属性正确（允许显示）
    logInfo("步骤10: 设置窗口属性");
    setAttribute(Qt::WA_DontShowOnScreen, false);
    logInfo("步骤10完成: 窗口属性已设置");
    
    // 处理所有待处理的事件，确保没有延迟的 paintEvent
    // 注意：此时 m_isDestroying = true，所以即使触发 paintEvent 也会直接返回
    logInfo("步骤11: 处理待处理事件 - m_isDestroying: " << m_isDestroying);
    QApplication::processEvents();
    logInfo("步骤11完成: 待处理事件已处理");
    
    // 重置析构标志（在显示窗口之前，所有准备工作完成后）
    logInfo("步骤12: 重置 m_isDestroying = false");
    m_isDestroying = false;
    
    // 显示窗口（在所有清理和准备完成后）
    logInfo("步骤13: 显示窗口");
    show();
    logInfo("步骤13: show() 调用完成");
    raise();
    logInfo("步骤13: raise() 调用完成");
    activateWindow();
    logInfo("步骤13完成: activateWindow() 调用完成");
    
    logInfo("========== startScreenshot 完成 ==========");
}

void ScreenshotWidget::updateToolbarPosition()
{
    if (!m_toolbar) return;
    
    int toolbarWidth = m_toolbar->sizeHint().width();
    int toolbarHeight = m_toolbar->sizeHint().height();
    
    // 如果有选中区域，工具栏显示在选中区域下边框的正下方
    if (!m_selectionRect.isEmpty()) {
        int x = m_selectionRect.center().x() - toolbarWidth / 2;
        int y = m_selectionRect.bottom() + 10;  // 选中区域下边框下方10像素
        
        // 确保工具栏不超出屏幕范围
        QRect screenRect = geometry();
        if (x < 0) x = 0;
        if (x + toolbarWidth > screenRect.width()) {
            x = screenRect.width() - toolbarWidth;
        }
        if (y + toolbarHeight > screenRect.height()) {
            // 如果下方空间不够，显示在选中区域上方
            y = m_selectionRect.top() - toolbarHeight - 10;
            if (y < 0) y = 0;
        }
        
        m_toolbar->setGeometry(x, y, toolbarWidth, toolbarHeight);
    } else {
        // 没有选中区域时，工具栏显示在屏幕底部居中
        QRect screenRect = geometry();
        int x = (screenRect.width() - toolbarWidth) / 2;
        int y = screenRect.height() - toolbarHeight - 20;
        m_toolbar->setGeometry(x, y, toolbarWidth, toolbarHeight);
    }
}

void ScreenshotWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    // 如果正在析构，不更新工具栏位置
    if (!m_isDestroying) {
        updateToolbarPosition();
    }
}

void ScreenshotWidget::finishTextInput()
{
    if (!m_textEdit || !m_textEdit->isVisible()) {
        return;
    }
    
    QString text = m_textEdit->toPlainText();
    logInfo("finishTextInput: 完成文字输入 - 文字: " << text);
    
    if (!text.isEmpty()) {
        saveState();
        QRect textRect = m_textEdit->geometry();
        QFont font = m_textEdit->font();
        TextElement* textElement = new TextElement(textRect, text, m_currentColor, m_penWidth, font);
        m_drawElements.append(textElement);
        logInfo("finishTextInput: 文字元素已添加 - 位置: " << textRect << " 文字: " << text);
    }
    
    m_textEdit->setVisible(false);
    m_textEdit->clearFocus();
    m_textEdit->clear();
    update();
}

QPixmap ScreenshotWidget::captureAllScreens()
{
    // 使用 ScreenshotService 获取全屏截图
    return ScreenshotService::instance().captureAllScreens();
}

void ScreenshotWidget::updateMask()
{
    if (m_fullScreenPixmap.isNull()) {
        return;
    }
    
    // 如果正在析构，不更新
    if (m_isDestroying) {
        return;
    }
    
    // 更新窗口大小和位置
    QRect totalRect;
    QList<QScreen*> screens = QApplication::screens();
    for (QScreen* screen : screens) {
        totalRect = totalRect.united(screen->geometry());
    }
    
    setGeometry(totalRect);
    
    // 只有在非析构状态下才调用 update
    // 但不在 startScreenshot 中调用，避免在元素删除后立即触发
    if (!m_isDestroying && isVisible()) {
        update();
    }
}

QPixmap ScreenshotWidget::getFinalScreenshot() const
{
    logInfo("getFinalScreenshot: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，返回空截图
    if (m_isDestroying) {
        logInfo("getFinalScreenshot: 正在析构，返回空截图");
        return QPixmap();
    }
    
    if (m_fullScreenPixmap.isNull()) {
        logInfo("getFinalScreenshot: 全屏截图为空");
        return QPixmap();
    }

    // 创建最终截图（只截取用户选择的区域，包含所有绘图）
    if (m_selectionRect.isEmpty()) {
        logError("getFinalScreenshot: 没有选择区域");
        return QPixmap();
    }
    
    // 从全屏截图中截取选中区域
    QRect sourceRect = m_selectionRect;
    sourceRect = sourceRect.intersected(m_fullScreenPixmap.rect());
    if (sourceRect.isEmpty()) {
        logError("getFinalScreenshot: 选择区域无效");
        return QPixmap();
    }
    
    QPixmap finalPixmap = m_fullScreenPixmap.copy(sourceRect);
    QPainter painter(&finalPixmap);
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制所有绘图元素（需要调整坐标，因为最终截图只包含选中区域）
    logInfo("getFinalScreenshot: 绘制所有绘图元素 - m_isDestroying: " << m_isDestroying << " 元素数量: " << m_drawElements.size());
    if (!m_isDestroying) {
        // 调整绘制坐标：将全局坐标转换为相对于选中区域的坐标
        painter.translate(-m_selectionRect.topLeft());
        drawAllElements(painter);
    }
    
    logInfo("getFinalScreenshot: 完成 - 最终截图尺寸: " << finalPixmap.size());
    return finalPixmap;
}

void ScreenshotWidget::drawAllElements(QPainter& painter) const
{
    logInfo("drawAllElements: 开始 - m_isDestroying: " << m_isDestroying << " 元素数量: " << m_drawElements.size());
    
    // 如果正在析构，不绘制任何元素
    if (m_isDestroying) {
        logInfo("drawAllElements: 正在析构，直接返回");
        return;
    }
    
    // 直接迭代列表，但在每次调用前检查
    // 注意：不能创建副本，因为我们需要检查元素是否仍在列表中
    for (int i = 0; i < m_drawElements.size(); ++i) {
        logInfo("drawAllElements: 迭代 " << i << "/" << m_drawElements.size());
        
        // 每次迭代前都检查析构标志
        if (m_isDestroying) {
            logInfo("drawAllElements: 检测到析构标志，中断绘制");
            return;
        }
        
        // 检查索引是否仍然有效
        if (i >= m_drawElements.size()) {
            logInfo("drawAllElements: 索引超出范围，中断");
            break;
        }
        
        DrawElement* element = m_drawElements[i];
        logInfo("drawAllElements: 元素 " << i << " 指针: " << (void*)element);
        
        if (!element) {
            logInfo("drawAllElements: 元素 " << i << " 为空，跳过");
            continue;
        }
        
        logInfo("drawAllElements: 准备调用 element->draw() - 工具类型: " << (int)element->tool);
        // 直接调用虚函数
        // 注意：如果对象正在被删除，m_isDestroying 应该已经被设置为 true
        element->draw(painter);
        logInfo("drawAllElements: 元素 " << i << " 绘制完成");
    }
    
    logInfo("drawAllElements: 完成");
}

void ScreenshotWidget::saveState()
{
    logInfo("saveState: 开始保存状态 - 元素数量: " << m_drawElements.size() << " m_isDestroying: " << m_isDestroying);

    // 如果正在析构，不保存状态
    if (m_isDestroying) {
        logInfo("saveState: 正在析构，跳过保存");
        return;
    }

    // [FDD-2025-03-021][AC-004] 检查历史栈是否达到上限
    if (m_historyStack.size() >= m_historyBudget.cap) {
        // 移除最旧的快照（栈底）
        if (!m_historyStack.isEmpty()) {
            // Qt 的 QStack 没有直接访问栈底的方法，需要转换为 QList
            QList<QList<DrawElement*>> tempList;
            while (!m_historyStack.isEmpty()) {
                tempList.prepend(m_historyStack.pop());
            }

            // 释放最旧的快照
            if (!tempList.isEmpty()) {
                QList<DrawElement*> oldest = tempList.takeFirst();
                for (DrawElement* elem : oldest) {
                    delete elem;
                }
                m_historyBudget.dropped++;
                qDebug() << "[HistoryBudget] Dropped oldest snapshot, total dropped:" << m_historyBudget.dropped;
            }

            // 恢复栈
            for (const auto& state : tempList) {
                m_historyStack.push(state);
            }
        }
    }

    // 保存当前状态到历史记录（深拷贝）
    QList<DrawElement*> currentState;
    for (int i = 0; i < m_drawElements.size(); ++i) {
        // 检查析构标志
        if (m_isDestroying) {
            logInfo("saveState: 检测到析构标志，中断保存");
            // 清理已创建的元素
            for (DrawElement* copy : currentState) {
                delete copy;
            }
            return;
        }

        if (i >= m_drawElements.size()) {
            break;
        }

        DrawElement* element = m_drawElements[i];
        if (!element) {
            continue;
        }

        logInfo("saveState: 处理元素 " << i << " - 工具类型: " << (int)element->tool);

        // 根据类型创建副本
        DrawElement* copy = nullptr;
        switch (element->tool) {
            case DrawTool::Rectangle: {
                RectangleElement* rect = static_cast<RectangleElement*>(element);
                copy = new RectangleElement(rect->rect, rect->color, rect->penWidth, rect->filled);
                break;
            }
            case DrawTool::Circle: {
                CircleElement* circle = static_cast<CircleElement*>(element);
                copy = new CircleElement(circle->rect, circle->color, circle->penWidth, circle->filled);
                break;
            }
            case DrawTool::Arrow: {
                ArrowElement* arrow = static_cast<ArrowElement*>(element);
                copy = new ArrowElement(arrow->startPoint, arrow->endPoint, arrow->color, arrow->penWidth);
                break;
            }
            case DrawTool::Pen: {
                PenElement* pen = static_cast<PenElement*>(element);
                PenElement* penCopy = new PenElement(pen->color, pen->penWidth);
                penCopy->points = pen->points;
                copy = penCopy;
                break;
            }
            case DrawTool::Mosaic: {
                MosaicElement* mosaic = static_cast<MosaicElement*>(element);
                copy = new MosaicElement(mosaic->rect, mosaic->color, mosaic->penWidth, mosaic->blockSize);
                break;
            }
            case DrawTool::Text: {
                TextElement* text = static_cast<TextElement*>(element);
                copy = new TextElement(text->rect, text->text, text->color, text->penWidth, text->font);
                break;
            }
            default:
                break;
        }
        if (copy) {
            currentState.append(copy);
            logInfo("saveState: 元素 " << i << " 副本已创建");
        } else {
            logInfo("saveState: 元素 " << i << " 副本创建失败");
        }
    }

    m_historyStack.push(currentState);
    m_historyBudget.current = m_historyStack.size();

    logInfo("saveState: 状态已保存 - 历史记录数量: " << m_historyStack.size()
            << "/" << m_historyBudget.cap << " dropped: " << m_historyBudget.dropped);
}

void ScreenshotWidget::undo()
{
    if (m_historyStack.isEmpty()) {
        logInfo("没有可撤销的操作");
        return;
    }
    
    // 临时设置标志，防止在清理过程中触发 paintEvent
    bool wasDestroying = m_isDestroying;
    m_isDestroying = true;
    
    // 清理当前元素
    for (DrawElement* element : m_drawElements) {
        delete element;
    }
    m_drawElements.clear();
    
    // 恢复上一个状态
    QList<DrawElement*> previousState = m_historyStack.pop();
    m_drawElements = previousState;
    
    // 恢复标志
    m_isDestroying = wasDestroying;
    
    // 只有在非析构状态下才更新
    if (!m_isDestroying) {
        update();
    }
    logInfo("撤销操作完成 - 剩余元素数: " << m_drawElements.size());
}

void ScreenshotWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    
    logInfo("========== paintEvent 被调用 ==========");
    logInfo("paintEvent: m_isDestroying = " << m_isDestroying);
    logInfo("paintEvent: isVisible = " << isVisible());
    logInfo("paintEvent: WA_DontShowOnScreen = " << testAttribute(Qt::WA_DontShowOnScreen));
    logInfo("paintEvent: m_fullScreenPixmap.isNull = " << m_fullScreenPixmap.isNull());
    logInfo("paintEvent: m_drawElements.size = " << m_drawElements.size());
    logInfo("paintEvent: m_currentElement = " << (void*)m_currentElement);
    
    // 如果正在析构，直接返回，避免调用虚函数
    if (m_isDestroying) {
        logInfo("paintEvent: 正在析构，直接返回");
        return;
    }
    
    // 检查窗口属性，如果设置了 WA_DontShowOnScreen，不绘制
    if (testAttribute(Qt::WA_DontShowOnScreen)) {
        logInfo("paintEvent: WA_DontShowOnScreen 已设置，直接返回");
        return;
    }
    
    logInfo("paintEvent: 开始绘制");
    
    QPainter painter(this);
    
    if (m_fullScreenPixmap.isNull()) {
        logInfo("paintEvent: 全屏截图为空，直接返回");
        return;
    }
    
    // 绘制全屏截图（作为背景）
    painter.drawPixmap(0, 0, m_fullScreenPixmap);
    
    // 如果有选择区域，未选中区域变暗，选中区域保持正常亮度
    if (!m_selectionRect.isEmpty()) {
        // 绘制暗色遮罩层（覆盖整个屏幕）
        QColor darkMaskColor(0, 0, 0, 120);  // 半透明黑色，降低未选中区域亮度
        painter.fillRect(rect(), darkMaskColor);
        
        // 清除选中区域的遮罩，使其保持正常亮度
        // 使用 SourceOver 模式重新绘制选中区域的原始内容
        painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
        QRect sourceRect = m_selectionRect;
        // 确保不超出截图范围
        sourceRect = sourceRect.intersected(m_fullScreenPixmap.rect());
        if (!sourceRect.isEmpty()) {
            QPixmap selectedRegion = m_fullScreenPixmap.copy(sourceRect);
            painter.drawPixmap(m_selectionRect.topLeft(), selectedRegion);
        }
        
        // 绘制选择区域的边框
        QPen borderPen(QColor(0, 120, 215), 2);  // 蓝色边框
        painter.setPen(borderPen);
        painter.setBrush(Qt::NoBrush);
        painter.drawRect(m_selectionRect);
        
        // 绘制四个角的控制点
        int cornerSize = 8;
        QRect cornerRect;
        
        // 左上角
        cornerRect = QRect(m_selectionRect.topLeft().x() - cornerSize/2,
                          m_selectionRect.topLeft().y() - cornerSize/2,
                          cornerSize, cornerSize);
        painter.fillRect(cornerRect, QColor(0, 120, 215));
        
        // 右上角
        cornerRect = QRect(m_selectionRect.topRight().x() - cornerSize/2,
                          m_selectionRect.topRight().y() - cornerSize/2,
                          cornerSize, cornerSize);
        painter.fillRect(cornerRect, QColor(0, 120, 215));
        
        // 左下角
        cornerRect = QRect(m_selectionRect.bottomLeft().x() - cornerSize/2,
                          m_selectionRect.bottomLeft().y() - cornerSize/2,
                          cornerSize, cornerSize);
        painter.fillRect(cornerRect, QColor(0, 120, 215));
        
        // 右下角
        cornerRect = QRect(m_selectionRect.bottomRight().x() - cornerSize/2,
                          m_selectionRect.bottomRight().y() - cornerSize/2,
                          cornerSize, cornerSize);
        painter.fillRect(cornerRect, QColor(0, 120, 215));
        
        // 显示选择区域的大小信息
        QString sizeText = QString("%1 x %2")
                          .arg(m_selectionRect.width())
                          .arg(m_selectionRect.height());
        QFont font = painter.font();
        font.setPointSize(12);
        painter.setFont(font);
        painter.setPen(Qt::white);
        painter.setBrush(QColor(0, 0, 0, 180));
        
        QRect textRect = painter.fontMetrics().boundingRect(sizeText);
        textRect.adjust(-4, -2, 4, 2);
        textRect.moveTopLeft(m_selectionRect.topLeft() + QPoint(0, -textRect.height() - 4));
        
        // 确保文本不超出屏幕
        if (textRect.top() < 0) {
            textRect.moveTopLeft(m_selectionRect.bottomLeft() + QPoint(0, 4));
        }
        
        painter.fillRect(textRect, QColor(0, 0, 0, 180));
        painter.drawText(textRect, Qt::AlignCenter, sizeText);
    } else {
        // 没有选择区域时，整个屏幕变暗
        QColor darkMaskColor(0, 0, 0, 120);
        painter.fillRect(rect(), darkMaskColor);
    }
    
    // 绘制所有绘图元素（检查析构标志）
    logInfo("paintEvent: 准备绘制绘图元素 - m_isDestroying: " << m_isDestroying);
    if (m_isDestroying) {
        logInfo("paintEvent: 正在析构，跳过绘制绘图元素");
        return;  // 如果正在析构，直接返回，不绘制任何元素
    }
    
    logInfo("paintEvent: 调用 drawAllElements - 元素数量: " << m_drawElements.size());
    drawAllElements(painter);
    logInfo("paintEvent: drawAllElements 完成");
    
    // 绘制当前正在绘制的元素（多重检查，防止在绘制过程中被删除）
    logInfo("paintEvent: 检查当前绘图元素 - m_currentElement: " << (void*)m_currentElement << " m_isDestroying: " << m_isDestroying);
    if (m_currentElement && !m_isDestroying) {
        logInfo("paintEvent: 绘制当前绘图元素 - 工具类型: " << (int)m_currentElement->tool);
        // 直接调用，因为我们已经检查了 m_isDestroying
        m_currentElement->draw(painter);
        logInfo("paintEvent: 当前绘图元素绘制完成");
    }
    
    logInfo("========== paintEvent 完成 ==========");
}

void ScreenshotWidget::mousePressEvent(QMouseEvent *event)
{
    logInfo("mousePressEvent: 被调用 - 按钮: " << (event->button() == Qt::LeftButton ? "左键" : "右键") 
            << " m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理鼠标事件
    if (m_isDestroying) {
        logInfo("mousePressEvent: 正在析构，忽略事件");
        return;
    }
    
    // 如果文字输入框可见，且点击位置不在输入框内，完成当前文字输入
    if (m_textEdit && m_textEdit->isVisible()) {
        QRect textEditRect = m_textEdit->geometry();
        if (!textEditRect.contains(event->pos())) {
            logInfo("mousePressEvent: 点击位置不在文字输入框内，完成当前文字输入");
            finishTextInput();
            // 继续处理点击事件（可能是选择区域、绘图或添加新文字）
        } else {
            // 点击在输入框内，不处理（让输入框自己处理）
            QWidget::mousePressEvent(event);
            return;
        }
    }
    
    if (event->button() == Qt::LeftButton) {
        if (m_currentTool == DrawTool::None) {
            // 选择模式
            logInfo("mousePressEvent: 选择模式");
            m_startPoint = event->pos();
            m_endPoint = m_startPoint;
            m_isSelecting = true;
            m_selectionRect = QRect();
            update();
        } else if (m_currentTool != DrawTool::None) {
            // 绘图工具：只能在选中区域内使用
            if (m_selectionRect.isEmpty()) {
                QMessageBox::information(this, "提示", "请先选择截图区域");
                return;
            }
            
            // 检查点击位置是否在选中区域内
            if (!m_selectionRect.contains(event->pos())) {
                QMessageBox::information(this, "提示", "只能在选中的区域内进行编辑");
                return;
            }
            
            if (m_currentTool == DrawTool::Pen) {
                // 画笔工具
                logInfo("mousePressEvent: 画笔工具 - 保存状态");
                saveState();
                logInfo("mousePressEvent: 创建 PenElement");
                m_currentElement = new PenElement(m_currentColor, m_penWidth);
                static_cast<PenElement*>(m_currentElement)->addPoint(event->pos());
                m_drawStartPoint = event->pos();
                m_drawEndPoint = event->pos();
                logInfo("mousePressEvent: PenElement 已创建 - 指针: " << (void*)m_currentElement);
            } else if (m_currentTool == DrawTool::Text) {
                // 文字工具：显示文字输入框
                logInfo("mousePressEvent: 文字工具 - 点击位置: " << event->pos());
                
                // 确保点击位置在选中区域内
                if (!m_selectionRect.contains(event->pos())) {
                    logInfo("mousePressEvent: 文字工具 - 点击位置不在选中区域内");
                    QMessageBox::information(this, "提示", "只能在选中的区域内添加文字");
                    return;
                }
                
                // 设置文字输入框的位置和大小
                QPoint textPos = event->pos();
                QSize textSize(200, 100);
                m_textEditRect = QRect(textPos, textSize);
                
                // 确保文字输入框完全在选中区域内
                if (!m_selectionRect.contains(m_textEditRect)) {
                    // 调整位置，确保输入框在选中区域内
                    if (m_textEditRect.right() > m_selectionRect.right()) {
                        m_textEditRect.moveRight(m_selectionRect.right());
                    }
                    if (m_textEditRect.bottom() > m_selectionRect.bottom()) {
                        m_textEditRect.moveBottom(m_selectionRect.bottom());
                    }
                    if (m_textEditRect.left() < m_selectionRect.left()) {
                        m_textEditRect.moveLeft(m_selectionRect.left());
                    }
                    if (m_textEditRect.top() < m_selectionRect.top()) {
                        m_textEditRect.moveTop(m_selectionRect.top());
                    }
                }
                
                logInfo("mousePressEvent: 文字工具 - 输入框位置: " << m_textEditRect);
                m_textEdit->setGeometry(m_textEditRect);
                m_textEdit->setVisible(true);
                m_textEdit->setFocus();
                m_textEdit->clear();
                m_textEdit->raise();  // 确保文字输入框在最上层
                update();
            } else {
                // 其他绘图工具（矩形、圆形、箭头、马赛克）
                logInfo("mousePressEvent: 绘图工具 - 工具类型: " << (int)m_currentTool << " 保存状态");
                saveState();
                m_drawStartPoint = event->pos();
                m_drawEndPoint = event->pos();
                
                QRect drawRect = QRect(m_drawStartPoint, m_drawEndPoint).normalized();
                
                logInfo("mousePressEvent: 创建绘图元素");
                switch (m_currentTool) {
                    case DrawTool::Rectangle:
                        m_currentElement = new RectangleElement(drawRect, m_currentColor, m_penWidth);
                        break;
                    case DrawTool::Circle:
                        m_currentElement = new CircleElement(drawRect, m_currentColor, m_penWidth);
                        break;
                    case DrawTool::Arrow:
                        m_currentElement = new ArrowElement(m_drawStartPoint, m_drawEndPoint, m_currentColor, m_penWidth);
                        break;
                    case DrawTool::Mosaic:
                        m_currentElement = new MosaicElement(drawRect, m_currentColor, m_penWidth, 10);
                        break;
                    default:
                        break;
                }
                logInfo("mousePressEvent: 绘图元素已创建 - 指针: " << (void*)m_currentElement);
            }
        }
    } else if (event->button() == Qt::RightButton) {
        // 右键：选择颜色
        logInfo("mousePressEvent: 右键 - 选择颜色");
        QColor color = QColorDialog::getColor(m_currentColor, this, "选择颜色");
        if (color.isValid()) {
            m_currentColor = color;
            logInfo("选择颜色: " << color.name());
        }
    }
}

void ScreenshotWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isSelecting) {
        // 选择模式
        m_endPoint = event->pos();
        m_selectionRect = QRect(m_startPoint, m_endPoint).normalized();
        // 更新工具栏位置
        updateToolbarPosition();
        update();
    } else if (m_currentElement) {
        // 绘图模式：限制在选中区域内
        QPoint pos = event->pos();
        
        // 如果当前有选中区域，限制绘图在选中区域内
        if (!m_selectionRect.isEmpty()) {
            // 限制坐标在选中区域内
            pos.setX(qBound(m_selectionRect.left(), pos.x(), m_selectionRect.right()));
            pos.setY(qBound(m_selectionRect.top(), pos.y(), m_selectionRect.bottom()));
        }
        
        m_drawEndPoint = pos;
        
        if (m_currentTool == DrawTool::Pen) {
            // 画笔：添加点
            static_cast<PenElement*>(m_currentElement)->addPoint(pos);
        } else {
            // 其他工具：更新矩形，但限制在选中区域内
            QRect drawRect = QRect(m_drawStartPoint, m_drawEndPoint).normalized();
            
            // 如果当前有选中区域，限制绘图矩形在选中区域内
            if (!m_selectionRect.isEmpty()) {
                drawRect = drawRect.intersected(m_selectionRect);
            }
            
            switch (m_currentTool) {
                case DrawTool::Rectangle:
                    static_cast<RectangleElement*>(m_currentElement)->rect = drawRect;
                    break;
                case DrawTool::Circle:
                    static_cast<CircleElement*>(m_currentElement)->rect = drawRect;
                    break;
                case DrawTool::Arrow:
                    static_cast<ArrowElement*>(m_currentElement)->endPoint = pos;
                    break;
                case DrawTool::Mosaic:
                    static_cast<MosaicElement*>(m_currentElement)->rect = drawRect;
                    break;
                default:
                    break;
            }
        }
        update();
    }
}

void ScreenshotWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_isSelecting) {
            // 选择模式
            m_isSelecting = false;
            m_endPoint = event->pos();
            m_selectionRect = QRect(m_startPoint, m_endPoint).normalized();
            
            // 如果选择区域太小，忽略
            if (m_selectionRect.width() < 5 || m_selectionRect.height() < 5) {
                m_selectionRect = QRect();
                update();
                return;
            }
            
            // 用户选择了区域，不需要立即截取，保持全屏截图用于显示
            // 选中区域会正常显示，未选中区域会变暗
            logInfo("mouseReleaseEvent: 用户选择了区域 - " << m_selectionRect);
            // 更新工具栏位置到选中区域下方
            updateToolbarPosition();
            update();
        } else if (m_currentElement) {
            // 绘图模式：完成绘图
            m_drawEndPoint = event->pos();
            
            if (m_currentTool == DrawTool::Pen) {
                // 画笔：添加最后一个点
                static_cast<PenElement*>(m_currentElement)->addPoint(event->pos());
            } else {
                // 其他工具：更新矩形
                QRect drawRect = QRect(m_drawStartPoint, m_drawEndPoint).normalized();
                
                switch (m_currentTool) {
                    case DrawTool::Rectangle:
                        static_cast<RectangleElement*>(m_currentElement)->rect = drawRect;
                        break;
                    case DrawTool::Circle:
                        static_cast<CircleElement*>(m_currentElement)->rect = drawRect;
                        break;
                    case DrawTool::Arrow:
                        static_cast<ArrowElement*>(m_currentElement)->endPoint = m_drawEndPoint;
                        break;
                    case DrawTool::Mosaic:
                        static_cast<MosaicElement*>(m_currentElement)->rect = drawRect;
                        break;
                    default:
                        break;
                }
            }
            
            // 添加到绘图元素列表
            m_drawElements.append(m_currentElement);
            m_currentElement = nullptr;
            update();
        }
    }
}

void ScreenshotWidget::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Escape) {
        // ESC 取消截图
        onExitButtonClicked();
    } else if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
        // Enter 完成文字输入或完成截图
        if (m_textEdit && m_textEdit->isVisible()) {
            // 如果文字输入框可见，完成文字输入
            finishTextInput();
        } else {
            // 完成截图
            onCompleteButtonClicked();
        }
    } else if (event->key() == Qt::Key_Z && event->modifiers() == Qt::ControlModifier) {
        // Ctrl+Z 撤销
        onUndoButtonClicked();
    } else {
        QWidget::keyPressEvent(event);
    }
}

void ScreenshotWidget::onToolButtonClicked()
{
    logInfo("onToolButtonClicked: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理
    if (m_isDestroying) {
        logInfo("onToolButtonClicked: 正在析构，忽略");
        return;
    }
    
    QPushButton* button = qobject_cast<QPushButton*>(sender());
    if (!button) {
        logInfo("onToolButtonClicked: sender 不是 QPushButton");
        return;
    }
    
    // 取消所有按钮的选中状态并恢复图标
    m_rectButton->setChecked(false);
    m_rectButton->setIcon(QIcon(":/resource/svg/rectangle.svg"));
    m_circleButton->setChecked(false);
    m_circleButton->setIcon(QIcon(":/resource/svg/circle.svg"));
    m_arrowButton->setChecked(false);
    m_arrowButton->setIcon(QIcon(":/resource/svg/arrow.svg"));
    m_penButton->setChecked(false);
    m_penButton->setIcon(QIcon(":/resource/svg/pen.svg"));
    m_mosaicButton->setChecked(false);
    m_mosaicButton->setIcon(QIcon(":/resource/svg/mosaic.svg"));
    m_textButton->setChecked(false);
    m_textButton->setIcon(QIcon(":/resource/svg/text.svg"));
    
    // 设置当前工具并更新图标
    if (button == m_rectButton) {
        m_currentTool = DrawTool::Rectangle;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/rectangle_active.svg"));
    } else if (button == m_circleButton) {
        m_currentTool = DrawTool::Circle;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/circle_active.svg"));
    } else if (button == m_arrowButton) {
        m_currentTool = DrawTool::Arrow;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/arrow_active.svg"));
    } else if (button == m_penButton) {
        m_currentTool = DrawTool::Pen;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/pen_active.svg"));
    } else if (button == m_mosaicButton) {
        m_currentTool = DrawTool::Mosaic;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/mosaic_active.svg"));
    } else if (button == m_textButton) {
        m_currentTool = DrawTool::Text;
        button->setChecked(true);
        button->setIcon(QIcon(":/resource/svg/text_active.svg"));
        // 如果当前有文字输入框显示，先完成它
        if (m_textEdit && m_textEdit->isVisible()) {
            finishTextInput();
        }
        // 文字工具不需要立即隐藏输入框，等待用户点击位置添加新文字
    }
    
    // 如果切换到其他工具，隐藏文字输入框
    if (m_textEdit && button != m_textButton) {
        // 如果输入框有内容，先完成它
        if (m_textEdit->isVisible() && !m_textEdit->toPlainText().isEmpty()) {
            finishTextInput();
        } else {
            m_textEdit->setVisible(false);
            m_textEdit->clearFocus();
        }
    }
    
    logInfo("选择工具: " << (int)m_currentTool);
}

void ScreenshotWidget::onUndoButtonClicked()
{
    logInfo("onUndoButtonClicked: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理
    if (m_isDestroying) {
        logInfo("onUndoButtonClicked: 正在析构，忽略");
        return;
    }
    
    undo();
}

void ScreenshotWidget::onSaveButtonClicked()
{
    logInfo("onSaveButtonClicked: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理
    if (m_isDestroying) {
        logInfo("onSaveButtonClicked: 正在析构，忽略");
        return;
    }
    
    // 检查是否已选择区域并截取
    if (m_fullScreenPixmap.isNull()) {
        QMessageBox::warning(this, "提示", "请先选择截图区域");
        return;
    }
    
    logInfo("onSaveButtonClicked: 获取最终截图");
    QPixmap finalPixmap = getFinalScreenshot();
    if (finalPixmap.isNull()) {
        QMessageBox::warning(this, "保存失败", "无法获取截图");
        return;
    }
    
    // 提示用户另存为
    auto& screenshotService = ScreenshotService::instance();
    QString defaultPath = screenshotService.getDefaultSavePath();
    QString defaultFileName = screenshotService.generateDefaultFileName();
    QString format = screenshotService.getConfig().getDefaultFormat();
    QString defaultFilePath = QDir(defaultPath).filePath(defaultFileName + "." + format);
    
    QString fileName = QFileDialog::getSaveFileName(
        this,
        "保存截图",
        defaultFilePath,
        "PNG Files (*.png);;JPEG Files (*.jpg);;All Files (*.*)"
    );
    
    if (!fileName.isEmpty()) {
        if (screenshotService.saveScreenshot(finalPixmap, fileName)) {
            QMessageBox::information(this, "保存成功", "截图已保存到文件");
            logInfo("截图已保存: " << fileName);
        } else {
            QMessageBox::warning(this, "保存失败", "无法保存截图到文件");
        }
    }
}

void ScreenshotWidget::onPinButtonClicked()
{
    m_isPinned = !m_isPinned;
    
    if (m_isPinned) {
        // 置顶：创建置顶窗口
        // 注意：这里需要创建一个置顶窗口来显示截图
        // 简化实现：只切换置顶状态
        setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
        show();
        m_pinButton->setIcon(QIcon(":/resource/svg/pin_active.svg"));
        logInfo("截图已置顶");
    } else {
        setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint);
        show();
        m_pinButton->setIcon(QIcon(":/resource/svg/pin.svg"));
        logInfo("取消置顶");
    }
}

void ScreenshotWidget::onExitButtonClicked()
{
    logInfo("onExitButtonClicked: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理
    if (m_isDestroying) {
        logInfo("onExitButtonClicked: 正在析构，忽略");
        return;
    }
    
    emit screenshotCancelled();
    m_isFinished = true;
    hide();
    logInfo("截图已取消");
}

void ScreenshotWidget::onCompleteButtonClicked()
{
    logInfo("onCompleteButtonClicked: 被调用 - m_isDestroying: " << m_isDestroying);
    
    // 如果正在析构，不处理
    if (m_isDestroying) {
        logInfo("onCompleteButtonClicked: 正在析构，忽略");
        return;
    }
    
    // 检查是否已选择区域并截取
    if (m_fullScreenPixmap.isNull()) {
        QMessageBox::warning(this, "提示", "请先选择截图区域");
        return;
    }
    
    logInfo("onCompleteButtonClicked: 获取最终截图");
    QPixmap finalPixmap = getFinalScreenshot();
    if (finalPixmap.isNull()) {
        QMessageBox::warning(this, "完成失败", "无法获取截图");
        return;
    }
    
    // 只复制到剪贴板，不提示保存
    auto& screenshotService = ScreenshotService::instance();
    screenshotService.copyToClipboard(finalPixmap);
    logInfo("onCompleteButtonClicked: 截图已复制到剪贴板");
    
    // 自动保存（根据配置）
    {
        ScreenshotConfig cfg = ScreenshotService::instance().getConfig();
        if (cfg.isAutoSave()) {
            if (!ScreenshotService::instance().saveScreenshot(finalPixmap)) {
                logWarning("onCompleteButtonClicked: 自动保存失败");
            } else {
                logInfo("onCompleteButtonClicked: 已自动保存到默认路径");
            }
        }
    }
    emit screenshotFinished(finalPixmap);
    m_isFinished = true;
    hide();
    logInfo("截图完成");
}
